package com.ctg.payroll2.action.payment;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jxl.write.WriteException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.ctg.payroll2.action.BaseAction;
import com.ctg.payroll2.bean.common.ColumnModel;
import com.ctg.payroll2.bean.filter.payment.PayDataFilter;
import com.ctg.payroll2.bean.po.payment.PayInput;
import com.ctg.payroll2.bean.po.payment.PayData;
import com.ctg.payroll2.bean.po.payment.PayDataTotal;
import com.ctg.payroll2.bean.po.payment.PayEmpdata;
import com.ctg.payroll2.service.common.PayrollUtilService;
import com.ctg.payroll2.service.payment.PayEmpdataService;
import com.ctg.payroll2.util.Constants;
import com.ctg.payroll2.util.xlsImport.JxlExport;
import com.ctg.platform.util.Page;
import com.ctg.platform.util.Parse;
import com.ctg.salary.service.PayDataService;
import com.googlecode.jsonplugin.annotations.JSON;

public class PayEmpdataAction extends BaseAction {
	private static final long serialVersionUID = 4866682142579345344L;
	/*
	 * 薪资计算结果
	 */
	private List<PayData> payDataList;
	/*
	 * 员工薪资额列表
	 */
	private Page payTotalResult;
	/*
	 * 薪资类别所对应雇员
	 */
	private List<PayEmpdata> existEmpList;
	/*
	 * 雇员工资额调整
	 */
	private PayInput payInput;

	/*
	 * 获取薪资计算结果服务
	 */
	private PayEmpdataService payEmpdataService;
	/*
	 * 薪资计算服务
	 */
	private PayDataService payDataService;
	/*
	 * 获取动态列字段服务
	 */
	private PayrollUtilService payrollUtilService;
	
	/*
	 * 薪资额查询过滤条件
	 */
	private PayDataFilter filter;
	
	/*
	 * 查询类型:
	 * "payData" 雇员工资明细数据, "calData" 计算工资并返回明细结果, 
	 * "payTotal" 返回雇员工资额列表, "empPayClass" 薪资类别所对就雇员
	 * "payInput" 返回工资调整结果
	 */
	private String queryType;
	/*
	 * 运行是否成功标记，成功为1，失败为0
	 */
	private int runFlag;
	
	ByteArrayInputStream bais ;
	
	@Override
	protected void commonOperations() {

	}

	@Override
	/*
	 * 批量添加薪资类别中对应雇员
	 */
	protected void createEntity() {
		if (filter == null) {
			filter = new PayDataFilter();
		}
		String added = request.getParameter("added");
		String classId = request.getParameter("classId");
		
		JSONArray addedArray = JSONArray.fromObject(added);
		List<PayEmpdata> addedList = new ArrayList<PayEmpdata>();
		for (int i = 0; i < addedArray.size(); i++) {
		   Object o = addedArray.get(i);
		   JSONObject jsonObject = JSONObject.fromObject(o);
		   PayEmpdata payEmpdata = (PayEmpdata) JSONObject.toBean(jsonObject, PayEmpdata.class);
		   payEmpdata.setCompany_code(currentUser.getCompanyCode());
		   payEmpdata.setPay_class_id(Long.parseLong(classId));
		   payEmpdata.setCreator_id(currentUser.getEmployeeId().toString());
		   
		   //查看当前薪资类别中是否已包含此员工
		   filter.setEmployeeId(payEmpdata.getEmployee_id());
		   filter.setPayTypeId(Long.parseLong(classId));
		   List<PayEmpdata> list = queryPayClassEmpList();
		   if(list.size() == 0){
			   addedList.add(payEmpdata);
		   }
		   filter.setEmployeeId(null);
		   filter.setPayTypeId(null);
		}
		
		if(addedList.size() != 0){
			payEmpdataService.insertPayEmpdata(addedList);
		}
	}

	@Override
	/*
	 * 批量删除薪资类别中对应雇员
	 */
	protected void deleteEntity() {
		String ids = "";
		String classId = request.getParameter("classId");
		
		String deleted = request.getParameter("deleted");
		JSONArray deletedArray = JSONArray.fromObject(deleted);
		for (int i = 0; i < deletedArray.size(); i++) {
		   Object o = deletedArray.get(i);
		   JSONObject jsonObject = JSONObject.fromObject(o);
		   PayEmpdata payEmpdata = (PayEmpdata) JSONObject.toBean(jsonObject, PayEmpdata.class);
		   if(i == 0){
			   ids += payEmpdata.getEmployee_id();
		   }else{
			   ids += "," + payEmpdata.getEmployee_id();
		   }
		}
		
		if(!ids.equals("")){
			String condition = "employee_id in (" + ids + ") and pay_class_id = " + classId;
			payEmpdataService.deletePayEmpDataBatch(condition);
		}
	}

	@SuppressWarnings({ "unchecked", "static-access" })
	@Override
	protected void exportXLS() {
		runFlag = 0;
		//获取数据内容
		List<PayDataTotal> payDataTotalList = (ArrayList)queryPayDataResult("excel").getResult();
		
		//获取数据列标题对应对字段
		List<ColumnModel> titles = new ArrayList();
		ColumnModel columnModel = new ColumnModel();
		columnModel.setHeader("雇员姓名");
		columnModel.setDataIndex("name");
		titles.add(columnModel);
		columnModel = new ColumnModel();
		columnModel.setHeader("薪资类别");
		columnModel.setDataIndex("payClassName");
		titles.add(columnModel);
		columnModel = new ColumnModel();
		columnModel.setHeader("年度月份");
		columnModel.setDataIndex("period");
		titles.add(columnModel);
		columnModel = new ColumnModel();
		columnModel.setHeader("薪资额");
		columnModel.setDataIndex("salary");
		titles.add(columnModel);
		
		//写excel文件
		try {
			//response.reset();
			//response.setContentType("application/x-msdownload");
			//response.setHeader("Content-Disposition", "attachment;filename="
				//	+ new String("export.xls".getBytes(), "utf-8"));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();  
			JxlExport.writeExcel(baos, payDataTotalList, titles);
			bais = new ByteArrayInputStream(baos.toByteArray());    
		} catch (WriteException e) {
			runFlag = 1;
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			runFlag = 2;
			e.printStackTrace();
		} catch (IntrospectionException e) {
			runFlag = 3;
			e.printStackTrace();
		} catch (IOException e) {
			runFlag = 4;
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			runFlag = 5;
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			runFlag = 6;
			e.printStackTrace();
		}
	}
	@JSON(serialize = false)
	public InputStream getExcelFile() {
		//System.out.println("afafafsadfasfdasfasf");
		return this.bais;
	}

	/*
	 * 获取薪资数据
	 */
	protected List<PayData> queryPayData(){
		List<ColumnModel> columnModelList = payrollUtilService.queryColumnModelList(filter.getPayTypeId());
		StringBuffer strFields = new StringBuffer();
//		String strFields = "";
		/*for(int i = 0; i < columnModelList.size(); i++){
			String strField = ((ColumnModel)columnModelList.get(i)).getDataIndex();
			if (i == 0){
				strFields += strField;
			}else{
				strFields += "," + strField;
			}
		}*/
//		filter.setDataFields(strFields);
		for (ColumnModel columnModel : columnModelList) {
			strFields.append(columnModel.getDataIndex()).append(",");
		}
		filter.setDataFields(strFields.length()>0?strFields.substring(0, strFields.length()-1):strFields.toString());
		List<PayData> dataList;
		try {
			dataList = payEmpdataService.queryPayDataList(filter);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return dataList;
	}
	
	/*
	 * 薪资计算并返回结果
	 */
	protected void calculatePayData(){
		try {
			//薪资计算历史编号
			Integer i1 = null;
			if(filter.getHisId() != null && !filter.getHisId().equals("")){
				i1 = Integer.parseInt(filter.getHisId().toString());
			}
			//薪资类别
			Integer i2 = Integer.parseInt(filter.getPayTypeId().toString());
			//计算某月薪资
			payDataService.generatePayData(context, i1, i2, filter.getMonthStart());
			runFlag = 1;
		} catch (Exception e) {
			runFlag = 0;
			e.printStackTrace();
		}
	}
	
	/*
	 * 获得薪资额数据列表
	 * resultType page 分页查询 excel 全部数据导出
	 */
	protected Page queryPayDataResult(String resultType){
		if (filter == null) {
			filter = new PayDataFilter();
		}
		filter.setCompanyCode(currentUser.getCompanyCode());
		if(resultType.equals("page")){
			filter.setStartIndex(Parse.toInteger(request.getParameter(Constants.START), 0));
			filter.setEndIndex(Parse.toInteger(request.getParameter(Constants.LIMIT), Constants.DEFAULT_PAGE_SIZE));
		}else if(resultType.equals("excel")){
			filter.setStartIndex(0);
			filter.setEndIndex(Parse.toInteger(request.getParameter(Constants.LIMIT), Constants.EXPORT_MAX_ROW));
		}
		return payEmpdataService.queryPayTotal(filter);
	}
	
	protected List<PayEmpdata> queryPayClassEmpList(){
		try {
			return payEmpdataService.queryPayClassEmpList(filter);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void queryEntity() {
		if(queryType.equals("payData")){
			payDataList = queryPayData();
		}else if(queryType.equals("calData")){
			calculatePayData();
		}else if(queryType.equals("payTotal")){
			payTotalResult = queryPayDataResult("page");
		}else if(queryType.equals("payClassEmp")){
			existEmpList = queryPayClassEmpList();
		}
	}

	@Override
	/*
	 * 调整雇员工资减项值，重新计算结果
	 */
	protected void retrieveEntity() {
		try {
			payInput.setCompany_code(currentUser.getCompanyCode());
			if(queryType != null && queryType.equals("payInput")){
				payInput = payEmpdataService.queryPayInput(payInput);
			}else{
				payInput.setModifier_code(currentUser.getEmployeeId());
				
				//保存输入数据
				payEmpdataService.saveCsPayInput(payInput);
				//重新计算此人薪资
				payDataService.generatePayData(context, null, 
						payInput.getEmployee_id(), payInput.getPeriod());
			}
		} catch (SQLException e) {
			runFlag = 1;
			e.printStackTrace();
		} catch (IndexOutOfBoundsException e){
			runFlag = 2;
		} catch (Exception e) {
			runFlag = 3;
			e.printStackTrace();
		}
	}

	@Override
	/*
	 * 批量更新薪资档案所对应员工
	 */
	protected void updateEntity() {
		deleteEntity();
		createEntity();
	}

	/**
	 * @param service 设置service
	 */
	public void setPayEmpdataService(PayEmpdataService payEmpdataService) {
		this.payEmpdataService = payEmpdataService;
	}
	
	public PayEmpdataService getPayEmpdataService() {
		return payEmpdataService;
	}

	public void setPayrollUtilService(PayrollUtilService payrollUtilService) {
		this.payrollUtilService = payrollUtilService;
	}

	public void setPayDataService(PayDataService payDataService) {
		this.payDataService = payDataService;
	}

	public List<PayData> getPayDataList() {
		return payDataList;
	}

	public void setPaymentDataList(List<PayData> payDataList) {
		this.payDataList = payDataList;
	}

	public Page getPayTotalResult() {
		return payTotalResult;
	}

	public void setPayTotalResult(Page payTotalResult) {
		this.payTotalResult = payTotalResult;
	}

	public List<PayEmpdata> getExistEmpList() {
		return existEmpList;
	}

	public void setExistEmpList(List<PayEmpdata> existEmpList) {
		this.existEmpList = existEmpList;
	}

	public String getQueryType() {
		return queryType;
	}

	public void setQueryType(String queryType) {
		this.queryType = queryType;
	}

	public PayDataFilter getFilter() {
		return filter;
	}

	public void setFilter(PayDataFilter filter) {
		this.filter = filter;
	}

	public int getRunFlag() {
		return runFlag;
	}

	public void setRunFlag(int runFlag) {
		this.runFlag = runFlag;
	}

	public PayInput getPayInput() {
		return payInput;
	}

	public void setPayInput(PayInput payInput) {
		this.payInput = payInput;
	}

}
